//
//  HMRefreshControl.swift
//  Weibo
//
//  Created by ZhuDong on 16/5/27.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
enum refreshState: Int {
    case Normal
    case Pulling
    case Refreshing
}
let keyPath = "contentOffset"
let refreshHeight: CGFloat = 60.0
class HMRefreshControl: UIControl {
    private var status: refreshState = .Normal{
        didSet{
            switch status {
            case refreshState.Normal:
                arrowView.hidden = false
                activityView.stopAnimating()
                tipLabel.text = "下拉起飞"
                UIView.animateWithDuration(0.25, animations: { 
                    self.arrowView.transform = CGAffineTransformIdentity
                })
                if oldValue == .Refreshing {
                    changeInset(false)
                }
            case refreshState.Pulling:
                tipLabel.text = "准备起飞"
                UIView.animateWithDuration(0.25, animations: {
                   self.arrowView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case refreshState.Refreshing:
                arrowView.hidden = true
                activityView.startAnimating()
                tipLabel.text = "正在起飞"
                sendActionsForControlEvents(.ValueChanged)
                changeInset(true)
            }
        }
    }
    private func changeInset(isAdd: Bool){
        var h: CGFloat = 0
        if isAdd {
            h = refreshHeight
        }else{
            h = -refreshHeight
        }
        var inset = (self.fatherView?.contentInset)!
        inset.top = inset.top + h
        self.fatherView?.contentInset = inset
        
    }
    func endRefreshing(){
        let time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 1))
        dispatch_after(time_t, dispatch_get_main_queue()) {
            self.status = .Normal
        }
    }
    private var fatherView: UIScrollView?
    lazy var arrowView: UIImageView = {
        let image = UIImage(named: "tableview_pull_refresh")
        let iV = UIImageView(image: image)
        iV.sizeToFit()
        return iV
    }()
    lazy var tipLabel: UILabel = {
        let l = UILabel()
        l.text = "下拉起飞"
        l.textColor = UIColor.greenColor()
        l.font = UIFont.systemFontOfSize(14)
        l.sizeToFit()
        return l
    }()
    lazy var activityView: UIActivityIndicatorView = {
        let ac = UIActivityIndicatorView()
        ac.activityIndicatorViewStyle = .Gray
        ac.startAnimating()
        return ac
    }()
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -refreshHeight, width: ScreenWidth, height: refreshHeight)
        super.init(frame: rect)
        self.backgroundColor = UIColor.orangeColor()
        setupUI()
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        //注册键值观察者
        if let fatherView = newSuperview as? UIScrollView{
            fatherView.addObserver(self, forKeyPath: keyPath, options: .New, context: nil)
            self.fatherView = fatherView
        }
        
    }
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        let offsetY = fatherView?.contentOffset.y
        if fatherView!.dragging {
            if status == .Normal && offsetY < -124 {
                status = .Pulling
            }else if status == .Pulling && offsetY > -124{
                status = .Normal
            }
        }else {
            if status == .Pulling{
              status = .Refreshing
            }
        }
    }
    deinit{
        fatherView?.removeObserver(self, forKeyPath: keyPath)
    }
    func setupUI(){
        addSubview(tipLabel)
        addSubview(arrowView)
        addSubview(activityView)
        tipLabel.snp_makeConstraints { (make) in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self)
        }
        arrowView.snp_makeConstraints { (make) in
            make.centerY.equalTo(self)
            make.right.equalTo(tipLabel.snp_left)
        }
        activityView.snp_makeConstraints { (make) in
            make.left.equalTo(tipLabel.snp_right).offset(StatusCellMargin)
            make.centerY.equalTo(self)
        }
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
